package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.model.admin.dtos.ChannelDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.common.base.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AdChannelServiceImpl extends BaseServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {
    /*继承ServiceImpl类(已经实现IService接口)   因此在Service里不必再继承IService （extends IService<AdChannel>） */
    /*范围限定在Mapper (extends BaseMapper<AdChannel> )*/


    @Override//一、根据名称查询频道列表分页
    public ResponseResult findByNameAndPage(ChannelDto dto) {
        //1.参数检测
        if (dto == null) return paramError;
        //分页参数检查   dto.checkParam();已经设置不传值的话默认赋值
        //2.安装名称模糊分页查询
        Page page = new Page(dto.page, dto.size);
        LambdaQueryWrapper<AdChannel> Wrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(dto.getName())) {
        /*
        isNotBlank : null判读   space判断  长度为0的判断
        isNotEmpty : null和长度为0的判断
        */
            Wrapper.like(AdChannel::getName, dto.getName());
        }
        IPage<AdChannel> iPage = page(page, Wrapper);
        //3.结果封装
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.size, (int) iPage.getTotal());
        result.setData(iPage.getRecords());
        return result;
    }


    @Override//二、新增频道信息
    public ResponseResult insert(AdChannel adChannel) {
        //1.检查参数
        if (null == adChannel) return paramError;
        //2.保存
        adChannel.setCreatedTime(new Date());
        save(adChannel);
        return paramSuccess;
    }


    @Override//三、修改频道信息
    public ResponseResult update(AdChannel adChannel) {
        //1.检查参数
        if (null == adChannel || adChannel.getId() == null) return paramError;
        //2.修改
        updateById(adChannel);
        return paramSuccess;
    }


    @Override//四、根据频道Id删除频道信息
    public ResponseResult deleteById(Integer id) {
        //1.检查参数
        if (id == null) {
            return paramError;
        }
        //2.判断当前频道是否存在 和 是否有效
        AdChannel adChannel = getById(id);
        if (adChannel == null) {
            return paramDataExist;
        }
        if (adChannel.getStatus()) {
            return paramError.error(1002, "频道有效不能删除");
        }
        //3.删除频道
        removeById(id);
        return paramSuccess;
    }
}
